package cn.itcast.bos.service.action.teke_delivary.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.action.teke_delivary.RoleService;
import cn.itcast.bos.web.Dao.teke_delivary.MenuRepository;
import cn.itcast.bos.web.Dao.teke_delivary.PermissionRepositoey;
import cn.itcast.bos.web.Dao.teke_delivary.RoleRepository;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleRepository;

	// 注入permissionRepository
	@Autowired
	private PermissionRepositoey permissionRepository;
	
	// 注入 MenuRepository
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Role> findByUser(User user) {
		// 基于用户查询角色
		// admin具有所有角色
		if (user.getUsername().equals("admin")) {
			return roleRepository.findAll();
		} else {
			return roleRepository.findByUser(user.getId());
		}

	}

	// 角色显示功能
	@Override
	public List<Role> findAll() {
		return roleRepository.findAll();
	}

	// 添加角色
	@Override
	public void saveRole(Role model, String[] permissionIds, String menuIds) {
		// 添加角色
		roleRepository.save(model);
		// 进行权限判断 bin关联权限
		if (permissionIds != null) {
			for (String permission : permissionIds) {
				Permission permissionid = permissionRepository.findOne(Integer.parseInt(permission));
				model.getPermissions().add(permissionid);
			}
		}
		// 进行菜单的关联   调用 StringUtils -- isNoneBlank   ---进行对menus的校验
		if (StringUtils.isNoneBlank(menuIds)) {
			// 对菜单数据进行切割
			String[] MenuIdssplit = menuIds.split(",");
			for (String menuid : MenuIdssplit) {
				Menu menus = menuRepository.findOne(Integer.parseInt(menuid));
				model.getMenus().add(menus);
			}
		}
	}

}
